/**
 * Created by zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/8/14
 * Time: 03:52
 */
$(function() {

    sendAjax('/v1/manager/program/detail.json', 'get', {id: id}, function (json) {
        var program = json.body.data;
        $('.program-title').text(program.title);
        $('.start-end-time').text(program.start_at + ' ~ ' + program.end_at);
        $('.apply-start-end').text(program.apply_start_at + ' ~ ' + program.apply_end_at);
        $('.check-start-end').text(program.check_start_at + ' ~ ' + program.check_end_at);
        $('.program-desc').val(program.desc);
    });
    sendAjax('/v1/manager/unselected/aparts.json', 'get', {program_id:id}, function (json) {
        var aparts = json.body.rows;
        $.each(aparts, function(n, v){
            var html = '<div class="col-md-4">';
            html += '<div class="form-group">';
            html += '<label class="col-sm-2 control-label">';
            html += '<input type="checkbox" value="'+v.id+'">';
            html += '<input type="hidden" class="apart-name" value="'+v.name+'">';
            html += '</label>';
            html += '<div class="col-sm-10 apart-content">';
            html += '<span class="apart-name"><a href="/manager/apart/view/'+v.id+'.html">'+v.name+'</a></span>';
            html += '</div>';
            html += '</div>';
            html += '</div>';
            $('.apart-list').append(html);
        });
    });

    $('.btn-save').on('click', function() {
        var data = [];
        $('input:checkbox:checked').each(function(){
            data.push({id:$(this).val(), name:$(this).next('.apart-name').val()});
        });
        if (checkForm(data)) {
            sendAjax('/v1/manager/program/add/aparts', 'post', {id:id, data:data}, function(json) {
                var div = '<div><input type="hidden" class="jump-url" value="/manager/program.html">' + json.message + '</div>';
                $('#action-tip .modal-body .tip-content').html(div);
                $('#action-tip').modal('show');
            });
        }
    });

    $('#action-tip').on('hide.bs.modal', function(){
        if ($(this).find('.jump-url').val()) {
            location.href = $(this).find('.jump-url').val();
        }
        $(this).find('.tip-content').text('');
    });
});

function checkForm(data) {
    if (data.length == 0) {
        $('#action-tip .modal-body .tip-content').text('请添加房源');
        $('#action-tip').modal('show');
        return false;
    }

    return true;
}